# -*- coding = utf-8 -*-
# @Time : 2021/4/29 15:14
# @File :usermodel.py
# @Software:PyCharm
from flask import Flask,request,jsonify,session
import re
from user import user_blue
# from blog import user
from werkzeug.security import generate_password_hash,check_password_hash
from peewee import *

db = MySQLDatabase('msg',host ='127.0.0.1',user='root',passwd='9953001')
db.connect()


class BaseModel(Model):
    class Meta:
        database = db  # 每一个继承BaseModel类的子类都是连接db表


class user(BaseModel):
    mobile = CharField()
    password = CharField()
    email = CharField()

class guanli(BaseModel):
    mobilegl = CharField()
    passwordgl = CharField()
    emailgl = CharField()

user.create_table()

guanli.create_table()

def enPassWord(password):#将明密码转化为hash码
    return generate_password_hash(password)#返回转换的hash码

def checkPassWord(enpassword,password):#第一参数是从数据查询出来的hash值，第二参数是需要检验的密码
    return check_password_hash(enpassword,password)#如果匹配返回true

# app = Flask(__name__)
# app.secret_key = 'please-generate-a-random-secret_key'
#
# app.register_blueprint(user_blue)

@user_blue.route('/register',methods=['POST'])
def register():
    req_dict = request.get_json()
    mobile = req_dict.get('mobile')
    password = req_dict.get('password')
    password2 = req_dict.get('password2')
    email = req_dict.get("email")

    if not all([mobile, password, password2,email]):
        return jsonify(errmsg='请求参数不完整')

    # 判断手机号格式
    if not re.match(r"1[34578]\d{9}", mobile):
        return jsonify(errmsg='手机号格式不正确')

    if not re.match(r"[a-zA-Z0-9]+@[a-zA-Z0-9]+\.[a-zA-Z0-9]+",email):
        return jsonify(errmsg='邮箱格式不正确')


    if password != password2:
        return jsonify(errmsg='两次密码不一致')

    password= enPassWord(password)

    p = user.get_or_none(user.mobile == mobile)
    if p == None:
        user.create(mobile=mobile, password=password, email=email)
        return jsonify(errmsg='注册成功')

    else:
        return jsonify(errmsg='已注册过，请登录')


@user_blue.route('/login', methods=['POST'])
def login():
    """登陆
    传递参数： 手机号、密码，
    格式为：json
    """
    # 获取参数
    req_dict = request.get_json()
    mobile = req_dict.get('mobile')
    password = req_dict.get('password')

    # 验证参数的完整性
    if not all([mobile, password]):
        return jsonify(errmsg='参数不完整')

    # 验证手机号的格式
    if not re.match(r'1[34578]\d{9}', mobile):
        return jsonify(errmsg='手机号格式错误')

    users=user.get_or_none(user.mobile==mobile)
    if users==None:
        return jsonify(errmsg='未注册')
    else:
        if checkPassWord(users.password,password)==True:
            session['mobile'] = mobile
            session['password'] = password
            return jsonify(errmsg='登录成功')
        elif checkPassWord(users.password,password)==False:
            return jsonify(errmsg='密码错误')

@user_blue.route('/index', methods=['GET'])
def index():
    """登录主页"""
    # 尝试从session中获取用户的名字
    mobile = session.get('mobile')
    # 如果session中的name存在，则表示已经登陆，否则未登录
    if mobile is None:
        return jsonify(errmsg='false')
    else:
        return jsonify(errmsg='true', data={"mobile": mobile,"zhuye":"欢迎来到个人主页"})

@user_blue.route('/index', methods=['DELETE'])
def logout():
    """退出"""
    # 清除session数据
    session.clear()
    return jsonify(errmsg='ok')

@user_blue.route('/change-password', methods=['GET', 'POST'])
def change_password():
    mobile = session.get('mobile')

    if mobile is None:
        return jsonify(errmsg='未登录，无法修改密码')
    else:
         p = user.get(user.mobile==mobile)
         req_dict = request.get_json()
         repassword = req_dict.get('repassword')
         newpassword= req_dict.get('newpassword')
         if checkPassWord(p.password,repassword)==True:
             newpassword = enPassWord(newpassword)
             user.update(password=newpassword).where(user.mobile ==mobile).execute()
             return jsonify(errmsg='修改成功！')
         else:
             return jsonify(errmsg='密码验证错误')

# if __name__ == '__main__':
#     app.run(debug=True)